//
//  DateManager.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/4.
//

import UIKit

class DateManager: NSObject {
    static let shared = DateManager()
    private override init() {}
    // 时间模型
    struct DateModel {
        var day : Int = 0
        var hour : Int = 0
        var minute : Int = 0
        var second : Int = 0
    }
    
    lazy var formatter : DateFormatter = {
        let formmatter = DateFormatter()
        formmatter.dateStyle = .medium
        formmatter.timeStyle = .short
        formmatter.timeZone = .current
        return formmatter
    }()
    
    //MARK:- 时间戳转时间 dateFormat传想获取的格式 例如：yyyy-MM-dd等
    func changeTimestampToCommonTime(_ timestamp : TimeInterval, _ dateFormat : String) -> String {
        formatter.dateFormat = dateFormat
        return formatter.string(from: Date(timeIntervalSince1970:timestamp))
    }
    
    //MARK:- 时间转时间戳 dateFormat传想获取的格式 例如：yyyy-MM-dd等
    func changeCommonTimeToTimestamp(_ time:String, _ dateFormat:String) -> TimeInterval {
        formatter.date(from: dateFormat)
        return formatter.date(from: time)!.timeIntervalSince1970
    }
    
    //MARK:- 时间戳和当前时间对比 返回时间模型
    func compareCurrentTime(_ compareDate : Int) -> DateModel {
        var dateModel : DateModel = DateModel()
        let date : Date = Date(timeIntervalSince1970: Double(compareDate))
        var timeInterval : TimeInterval = date.timeIntervalSince1970
        timeInterval = fabs(timeInterval)
        
        dateModel.second = Int(timeInterval.truncatingRemainder(dividingBy: 60))
        dateModel.minute = Int((timeInterval / 60.0).truncatingRemainder(dividingBy: 60))
        dateModel.hour = Int(timeInterval / 3600)
        dateModel.day = Int(timeInterval / 3600 / 24)
        
        return dateModel
    }
    
    //MARK:- 倒计时时间戳转换 返回时间模型
    func changeCountDownTime(_ countTime : Int) -> DateModel {
        var dateModel : DateModel = DateModel()
        dateModel.second = Int(Double(countTime).truncatingRemainder(dividingBy: 60))
        dateModel.minute = Int((Double(countTime) / 60.0).truncatingRemainder(dividingBy: 60))
        dateModel.hour = Int(countTime / 3600)
        dateModel.day = Int(countTime / 3600 / 24)
        return dateModel
    }
}
